package com.zjm.zdk.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class Client {

    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("localhost", 8080));
        while (!socketChannel.finishConnect()) {
            Thread.yield();
        }
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入：");
        // 发送内容
        String msg = scanner.nextLine();
        ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
        while (buffer.hasRemaining()) {
            socketChannel.write(buffer);
        }
        // 读取响应
        ByteBuffer reqBuffer = ByteBuffer.allocate(1024);
        while (socketChannel.isOpen() && socketChannel.read(reqBuffer) != -1) {
            if (reqBuffer.position() > 0) {
                break;
            }
        }
        reqBuffer.flip();
        byte[] content = new byte[reqBuffer.limit()];
        reqBuffer.get(content);
        System.out.println("收到服务端响应");
        System.out.println(new String(content));
        scanner.close();
        socketChannel.close();
    }

}
